package 可视化算法.概率模拟算法.蒙特卡洛算法求PI值;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.util.LinkedList;

/**
 * @author MT
 * 算法可视化中的MVC
 * @date 2019-11-29 10:03
 */
public class AlgoVisualizer {

    private MonteCarloPiData data;
    private AlgoFrame frame;
    private int N;

    private static int DELAY = 1;


    public AlgoVisualizer(int sceneWidth, int sceneHeight, int N) {

        if (sceneWidth != sceneHeight) {
            throw new IllegalArgumentException("This demo must be run in a square");
        }
        this.N = N;

        Circle circle = new Circle(sceneWidth / 2, sceneHeight / 2, sceneWidth / 2);
        data = new MonteCarloPiData(circle);

        EventQueue.invokeLater(() -> {
            this.frame = new AlgoFrame("蒙特卡洛算法", sceneWidth, sceneHeight);
            // 添加键盘事件
            this.frame.addKeyListener(new AlgoKeyListener());
            // 添加鼠标事件
            this.frame.addMouseListener(new AlgoMouseListener());
            new Thread(() -> {
                this.run();
            }).start();
        });
    }

    /**
     * 动画逻辑
     */
    private void run() {

        for (int i = 0; i < N; i++) {

            if (i % 100 == 0) {

                frame.render(data);
                AlgoVisHelper.pause(DELAY);
                System.out.println(data.estimatePi());
            }

            int x = (int) (Math.random() * frame.getCanvasWidth());
            int y = (int) (Math.random() * frame.getCanvasHeight());

            data.addPoint(new Point(x,y));
        }
    }


    private class AlgoKeyListener extends KeyAdapter {
    }

    private class AlgoMouseListener extends MouseAdapter {
    }
}
